package com.jxb.test20241216;


import com.jxb.first.ListNode;

public class MergeTwoSortLists_21 {

    public static void main(String[] args) {
        ListNode a = new ListNode(1);
        a.setNext(new ListNode(3));
        ListNode b = new ListNode(2);
        ListNode listNode = mergeTwoSortLists(a, b);
        System.out.println(listNode);
    }

    //循环+指针
    public static ListNode mergeTwoSortLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode p = new ListNode();
        while (l1 != null && l2 !=null) {
            if (l1.val < l2.val) {
                p.next = l1;
                l1 = l1.next;
            }else {
                p.next = l2;
                l2 = l2.next;
            }
        }
        if (l1 != null) {
            p.next = l1;
        }
        if (l2 != null) {
            p.next = l2;
        }
        return p.next;
    }

    //递归
    //l1的节点值小于l2的节点值，将l1的下一个节点置为下一轮l1的next节点与l2节点的比较
    //若大于，则相反
    public static ListNode mergeTwoSortLists1(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        if (l1.val < l2.val) {
            l1.next = mergeTwoSortLists1(l1.next,l2);
            return l1;
        }
        l2.next = mergeTwoSortLists1(l2.next,l1);
        return l2;
    }

}
